const express = require('express');
const router = express.Router();
const redisClient = require('../redis/client');
const cacheMiddleware = require('../middleware/cache');

// 模拟用户数据
const users = [
  { id: 1, name: '张三', email: 'zhangsan@example.com' },
  { id: 2, name: '李四', email: 'lisi@example.com' },
  { id: 3, name: '王五', email: 'wangwu@example.com' },
];

// 获取所有用户（带缓存）
router.get('/', cacheMiddleware(60), (req, res) => {
  // 模拟数据库查询延迟
  setTimeout(() => {
    res.json(users);
  }, 1000);
});

// 根据ID获取用户
router.get('/:id', cacheMiddleware(120), (req, res) => {
  const userId = parseInt(req.params.id);
  const user = users.find(u => u.id === userId);
  
  if (!user) {
    return res.status(404).json({ error: '用户不存在' });
  }

  // 模拟数据库查询延迟
  setTimeout(() => {
    res.json(user);
  }, 500);
});

// 创建用户
router.post('/', async (req, res) => {
  const { name, email } = req.body;
  
  if (!name || !email) {
    return res.status(400).json({ error: '姓名和邮箱是必填项' });
  }

  const newUser = {
    id: users.length + 1,
    name,
    email
  };

  users.push(newUser);

  try {
    // 清除相关的缓存
    await redisClient.del('cache:/api/users');
    console.log('Cleared users cache');
    
    res.status(201).json(newUser);
  } catch (error) {
    res.status(500).json({ error: '创建用户失败' });
  }
});

// 更新用户
router.put('/:id', async (req, res) => {
  const userId = parseInt(req.params.id);
  const { name, email } = req.body;
  
  const userIndex = users.findIndex(u => u.id === userId);
  
  if (userIndex === -1) {
    return res.status(404).json({ error: '用户不存在' });
  }

  users[userIndex] = { ...users[userIndex], name, email };

  try {
    // 清除相关的缓存
    await redisClient.del('cache:/api/users');
    await redisClient.del(`cache:/api/users/${userId}`);
    console.log('Cleared user caches');
    
    res.json(users[userIndex]);
  } catch (error) {
    res.status(500).json({ error: '更新用户失败' });
  }
});

// 删除用户
router.delete('/:id', async (req, res) => {
  const userId = parseInt(req.params.id);
  const userIndex = users.findIndex(u => u.id === userId);
  
  if (userIndex === -1) {
    return res.status(404).json({ error: '用户不存在' });
  }

  const deletedUser = users.splice(userIndex, 1)[0];

  try {
    // 清除相关的缓存
    await redisClient.del('cache:/api/users');
    await redisClient.del(`cache:/api/users/${userId}`);
    console.log('Cleared user caches');
    
    res.json({ message: '用户删除成功', user: deletedUser });
  } catch (error) {
    res.status(500).json({ error: '删除用户失败' });
  }
});

module.exports = router;